//
//  StatusPictureView.swift
//  weibo
//
//  Created by yellow on 15/10/21.
//  Copyright © 2015年 yellow. All rights reserved.
//



import UIKit
import SDWebImage

//定义常量

//cell间的间隔
let itemMargin:CGFloat = 10

/// cell重用标示符
let statusPictureViewCellId = "statusPictureViewCellId"


class StatusPictureView: UICollectionView {
    
    var model:StatusDetailViewModel?{
        didSet{
            sizeToFit()
            
            //如果设置了model后不刷新数据源，cell回重用，不再取读取数据源的方法了
            reloadData()
        }
    }
    
    //任何想要根据一定条件改变视图大小的，都可以重写该方法，前提是需要调用 sizeToFit()
    override func sizeThatFits(size: CGSize) -> CGSize {
        return getPictureViewSize()
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor.clearColor()
        
        dataSource = self
        delegate = self
        
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: statusPictureViewCellId)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


// MARK: - 数据源,代理
extension StatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return (model?.thumbnailUrls?.count)!
        //因为thumbnailUrls有可能会空，所以需要使用可选项替换，不然会报野指针错误
        return model?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureViewCellId, forIndexPath: indexPath) as! StatusPictureViewCell
        cell.pictureURL = model?.thumbnailUrls![indexPath.item]
        return cell
    }
    
    
    // 点击配图item时被调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //构建通知传递的字典
        let selectedStatusPictureDict = [
                                         StatusPictureViewCellSelectedIndexPathKey:indexPath,
                                         StatusPictureViewCellSelectedURLKey:model!.thumbnailUrls!
                                        ]
        //发送带有选中配图cell的indexPath和urls通知，(主要是HomeTableViewController来接收通知)
        NSNotificationCenter.defaultCenter().postNotificationName(StatusPictureViewCellSelectedNotification, object: self, userInfo: selectedStatusPictureDict)
    }
}


// MARK: - 计算需要展现的大小
extension StatusPictureView{
    
    /// - returns: 真个view的大小
    func getPictureViewSize()  ->CGSize{
        
        //一行最多显示3张图片
        let rowCount:CGFloat = 3
        //view显示的最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width-2*itemMargin
        //计算出单个item的宽度
        let itemWidth = (maxWidth - 2 * itemMargin)/3
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        //设置布局对象中item的大小
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        //获取配图count,如果URL数组则返回0
        let count = model?.thumbnailUrls?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1{
            //设置默认大小
            var size = CGSizeMake(150, 120)
            //获取缓存图片
            
            let singleURL = model?.thumbnailUrls![0]
            if let singleImg = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(singleURL?.absoluteString){
                size = singleImg.size
                
                //处理极宽或是极窄的图片
                size.width = size.width < 40 ? 40 : size.width
                if size.width > 300{
                    let h:CGFloat = 150
                    //为保证图片不变形，按等比缩放
                    size.height = size.width*h/size.height
                    size.width = h
                }
            }
        
            // TODO:先设置为默认大小
            
            layout.itemSize = size
            return size
        }
        
        //2*2
        if count == 4{
            let width = 2*itemWidth+itemMargin
            return CGSizeMake(width, width)
        }
        
        //其他情况安装九宫格来显示
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let w = rowCount * itemWidth + (rowCount-1) * itemMargin
        let h = row * itemWidth + (row-1) * itemMargin
        return CGSizeMake(w, h)
    }

}


/// 定义collectionCell
private class StatusPictureViewCell:UICollectionViewCell{

    var pictureURL:NSURL?{
    
        didSet{
            //options参数中第一个时超时候，加入黑名单，第二个参数是即使有缓冲，url中的图片变了也会去服务器读取
            pictureImageView.sd_setImageWithURL(pictureURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached])
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(){

        //添加控件到contentView之外，可能会出现控件重用的问题,因为我们社长约束是针对于contentView设置的
        contentView.addSubview(pictureImageView)
        
        //自动布局
        pictureImageView.snp_makeConstraints { (make) -> Void in
            //设置edges(边缘) 是contentView有多大，图片就设置多大
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    
 /// 懒加载控件
    lazy var pictureImageView:UIImageView = {
        let imageView = UIImageView()
        
        //图片填充模式为不压缩比例，填满view的size，这样出来的图片(人物)不会变形
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        //多余部分减掉
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
}
